Find Sum of Natural Numbers Using Recursion

Course- Python >

Source Code


# Python program to find the sum of natural numbers up to n using recursive function

def recur_sum(n):
   """Function to return the sum
   of natural numbers using recursion"""
   if n <= 1:
       return n
   else:
       return n + recur_sum(n-1)

# take input from the user
num = int(input("Enter a number: "))

if num < 0:
   print("Enter a positive number")
else:
   print("The sum is",recur_sum(num))

Output


Enter a number: 16
The sum is 136

In this program, we ask the user for a number and use recursive function recur_sum() to compute the sum up to that number.